from rest_framework import serializers
from .models import Cart
from goods.models import SKU
from users.models import User

class CartsSerializer(serializers.ModelSerializer):
    sku_id = serializers.IntegerField(required=True,min_value=1,label='商品id')
    count = serializers.IntegerField(required=True,min_value=1,label='商品数量')
    selected = serializers.BooleanField(default=True,label='商品选中状态')

    class Meta:
        model  = Cart
        fields = ['sku_id','count','selected']

    def validate(self, attrs):

        sku_id = attrs.get('sku_id')
        count = attrs.get('count')

        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在或已下架')

        if sku.stock < count:
            raise serializers.ValidationError('库存不足')

        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        user_obj = User.objects.get(pk=user.id)
        validated_data['user'] = user_obj

        cart = super().create(validated_data)

        return cart






